package com.ktwlsoft.archivemanage.domain.business.businessService.register;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ktwlsoft.archivemanage.config.exception.ResultException;
import com.ktwlsoft.archivemanage.domain.business.businessService.NotifyMessageScheduleTask;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.AccountRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.ArchiveUnitRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.InforConstRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.InfrastructureRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.register.AccountRegisterService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.sms.SmsService;
import com.ktwlsoft.archivemanage.domain.dao.entity.*;
import com.ktwlsoft.archivemanage.domain.dao.entity.register.AccountRegister;
import com.ktwlsoft.archivemanage.domain.dao.entity.sms.SendSms;
import com.ktwlsoft.archivemanage.domain.dao.repository.UnitMemberMapper;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import com.ktwlsoft.archivemanage.service.security.UserPrincipal;
import com.ktwlsoft.archivemanage.service.utils.SnowFlake;
import com.ktwlsoft.archivemanage.service.utils.UserUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 注册
 *
 * @author Name on 2020/7/9 10:47
 * @version 1.0
 */
@Component
public class RegisterService {

    /**账号注册业务层接口实现类*/
    private final AccountRegisterService accountRegisterService;

    /**立档单位业务层接口实现类*/
    private final ArchiveUnitRepositoryService unitRepositoryService;

    /**账号业务层接口实现类*/
    private final AccountRepositoryService accountRepositoryService;

    /**立档单位人员信息数据层服务类*/
    private final UnitMemberMapper unitMemberMapper;

    /**信息化建设*/
    private final InforConstRepositoryService inforConstRepositoryService;

    /**基础设施信息*/
    private final InfrastructureRepositoryService infrastructureRepositoryService;

    /**短信服务接口实现*/
    private final SmsService smsService;

    private final PasswordEncoder passwordEncoder;

    /**消息通知*/
    private final NotifyMessageScheduleTask notifyMessageScheduleTask;

    public RegisterService(AccountRegisterService accountRegisterService, ArchiveUnitRepositoryService unitRepositoryService, AccountRepositoryService accountRepositoryService, UnitMemberMapper unitMemberMapper, InforConstRepositoryService inforConstRepositoryService, InfrastructureRepositoryService infrastructureRepositoryService, SmsService smsService, PasswordEncoder passwordEncoder, NotifyMessageScheduleTask notifyMessageScheduleTask) {
        this.accountRegisterService = accountRegisterService;
        this.unitRepositoryService = unitRepositoryService;
        this.accountRepositoryService = accountRepositoryService;
        this.unitMemberMapper = unitMemberMapper;
        this.inforConstRepositoryService = inforConstRepositoryService;
        this.infrastructureRepositoryService = infrastructureRepositoryService;
        this.smsService = smsService;
        this.passwordEncoder = passwordEncoder;
        this.notifyMessageScheduleTask = notifyMessageScheduleTask;
    }

    /**
      * 注册审核列表 on 2020/7/9 12:02
      *
      * @param keyWords 关键字
      * @param type 类型:待审核(WAIT_FOR),已通过(ADOPT),已打回(REPULSE)
      * @return Result<?>
      */
    public Result<?> findPage(int pn,int pageSize,String keyWords,String type){
        JSONObject object = new JSONObject();
        object.put("keyWords",keyWords != null?keyWords.trim():null);
        object.put("type",type != null?type.trim():null);
        PageInfo<AccountRegister> pageInfo = accountRegisterService.examinePage(pn,pageSize,object);
        return Result.ok(pageInfo);
    }

    /**
      * 注册新增 on 2020/7/9 10:52
      *
      * @param request request
      * @return Result<?>
      */
    @Transactional(rollbackFor = Exception.class)
    public Result<?> save(AccountRegister request){
        if(request.getUnitName() == null || "".equals(request.getUnitName().trim())){
            return Result.body(request.getUnitName(), ResultType.CHECK_ERROR).withMessage("单位名称为空");
        }
        if(request.getAccount() == null || "".equals(request.getAccount().trim())){
            return Result.body(request.getUnitName(), ResultType.CHECK_ERROR).withMessage("账号为空");
        }
        if(request.getDepartLeader() == null || "".equals(request.getDepartLeader().trim())){
            return Result.body(request.getUnitName(), ResultType.CHECK_ERROR).withMessage("分管领导为空");
        }
        if(request.getRecorder() == null || "".equals(request.getRecorder().trim())){
            return Result.body(request.getUnitName(), ResultType.CHECK_ERROR).withMessage("档案员为空");
        }
        if(request.getRecorderTele() == null || "".equals(request.getRecorderTele().trim())){
            return Result.body(request.getUnitName(), ResultType.CHECK_ERROR).withMessage("档案员电话为空");
        }
        int i = unitRepositoryService.findByUnitName(request.getUnitName());
        AccountRegister register = new AccountRegister();
        register.setUnitName(request.getUnitName());
        List<AccountRegister> registerList = accountRegisterService.findList(register);
        if(i > 0 || (registerList != null && registerList.size() > 0)){
            return Result.body(request.getUnitName(), ResultType.CHECK_ERROR).withMessage("该单位已存在");
        }
        Account account = accountRepositoryService.getByUserName(request.getAccount());
        register.setAccount(request.getAccount());
        register.setUnitName(null);
        List<AccountRegister> accountRegisters = accountRegisterService.findList(register);
        if(account != null || (accountRegisters != null && accountRegisters.size() > 0)){
            return Result.body(request.getUnitName(), ResultType.CHECK_ERROR).withMessage("该账号已存在");
        }
        Account checkUnique = new Account();
        checkUnique.setTeleNum(request.getRecorderTele());
        checkUnique.setRoleName("立档单位");
        List<Account> accounts = accountRepositoryService.checkUnique(checkUnique);
        register.setAccount(null);
        register.setUnitName(null);
        register.setRecorderTele(request.getRecorderTele());
        List<AccountRegister> accountRegisters1 = accountRegisterService.findList(register);
        if((accounts != null && accounts.size() > 0) || (accountRegisters1 != null && accountRegisters1.size() > 0)){
            return Result.body(request.getUnitName(), ResultType.CHECK_ERROR).withMessage("该电话号码已存在");
        }
        account = UserPrincipal.getCurrentUser();
        if(account == null){
            account = new Account();
        }
        request.setId(SnowFlake.getNextId());
        request.setState(AccountRegister.WAIT_FOR);
        request.setDataState(1);
        request.setCreateName(account.getRealName());
        request.setCreateId(account.getId());
        request.setCreateTime(new Date());
        request.setUpdateName(account.getRealName());
        request.setUpdateId(account.getId());
        request.setUpdateTime(new Date());
        try {
            accountRegisterService.insert(request);
            //新增消息通知
            notifyMessageScheduleTask.addRegister(request);
        }catch (Exception e){
            e.printStackTrace();
            throw new ResultException("操作过程中出现错误",ResultType.BUSINESS_ERROR);
        }
        return Result.ok(request.getId());
    }

    /**
      * 审核打回 on 2020/7/9 12:17
      *
      * @param id id
      * @param reason reason
      * @return Result<?>
      */
    public Result<?> repulse(Long id,String reason){
        AccountRegister register = accountRegisterService.getById(id);
        if(register == null){
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        Account account = UserPrincipal.getCurrentUser();
        if(account == null){
            account = new Account();
        }
        register.setState(AccountRegister.REPULSE);
        register.setReason(reason);
        register.setUpdateName(account.getRealName());
        register.setUpdateId(account.getId());
        register.setUpdateTime(new Date());
        try {
            accountRegisterService.update(register);
        }catch (Exception e){
            e.printStackTrace();
            return Result.body(id, ResultType.BUSINESS_ERROR).withMessage("操作过程中出现错误");
        }
        //发送短信
        SendSms sendSms = new SendSms();
        //短信渠道
        sendSms.setSmsChannel("1");
        //短信模板编码
        sendSms.setSmsTemplateEncoded("sendRegisterRepulse");
        //待发送手机号
        String[] strings = new String[]{register.getRecorderTele()};
        sendSms.setPhoneNumbers(strings);
        //短信模板变量
        Map<String, String> map = new HashMap<>();
        map.put("reason", reason);
        sendSms.setParamMap(map);
        return smsService.sendSms(sendSms);
    }

    /**
      * 审核通过 on 2020/7/9 14:40
      *
      * @param id id
      * @return Result<?>
      */
    public Result<?> adopt(Long id){
        AccountRegister register = accountRegisterService.getById(id);
        if(register == null){
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        Account user = UserPrincipal.getCurrentUser();
        if(user == null){
            user = new Account();
        }
        //注册
        register.setState(AccountRegister.ADOPT);
        register.setUpdateName(user.getRealName());
        register.setUpdateId(user.getId());
        register.setUpdateTime(new Date());
        //用户账号
        Account account = new Account();
        account.setUserName(register.getAccount());
        account.setRealName(register.getRecorder());
        account.setTeleNum(register.getRecorderTele());
        account.setSex(true);
        account.setEnable(true);
        account.setPassword(passwordEncoder.encode("Ywzd000111%@@"));
        account.setPasswordStrength(UserUtils.testingPasswordStrength("Ywzd000111%@@"));
        account.setRoleId(0L);
        account.setRoleName("立档单位");
        account.setCreator(user.getRealName());
        account.setCreatorId(user.getId());
        //立档单位
        ArchiveUnit archiveUnit = new ArchiveUnit();
        archiveUnit.setAccountId(account.getId());
        archiveUnit.setPid(register.getPid());
        archiveUnit.setUnitName(register.getUnitName());
        archiveUnit.setTreeLevel(archiveUnit.getPid() != null && archiveUnit.getPid() != 0?2:1);
        archiveUnit.setUnitNature(register.getUnitNature());
        archiveUnit.setUnitTele(register.getUnitTele());
        archiveUnit.setAccount(register.getAccount());
        archiveUnit.setEnable(true);
        archiveUnit.setAddress(register.getAddress());
        archiveUnit.setPassword(passwordEncoder.encode("Ywzd000111%@@"));
        archiveUnit.setCreator(user.getRealName());
        archiveUnit.setCreatorId(user.getId());
        //人员信息
        UnitMember unitMember=new UnitMember();
        unitMember.setUnitId(archiveUnit.getId());
        unitMember.setDepartLeaderId(SnowFlake.getNextId());
        unitMember.setDepartLeader(register.getDepartLeader());
        unitMember.setRecorder(register.getRecorder());
        unitMember.setRecorderId(account.getId());
        unitMember.setRecorderTele(register.getRecorderTele());
        unitMember.setRecorderSex(account.getSex());
        unitMember.setCreator(user.getRealName());
        unitMember.setCreatorId(user.getId());
        unitMember.setRecorderIdentityNum("");
        //信息化建设
        InforConst inforConst=new InforConst();
        inforConst.setUnitId(archiveUnit.getId());
        inforConst.setCreator(user.getRealName());
        inforConst.setCreatorId(user.getId());
        //基础设施信息
        Infrastructure infrastructure=new Infrastructure();
        infrastructure.setUnitId(archiveUnit.getId());
        infrastructure.setCreator(user.getRealName());
        infrastructure.setCreatorId(user.getId());
        try {
            accountRegisterService.update(register);
            accountRepositoryService.insert(account);
            unitRepositoryService.insert(archiveUnit);
            unitMemberMapper.addUnitMemberInfo(unitMember);
            inforConstRepositoryService.addInforConstItem(inforConst);
            infrastructureRepositoryService.addInfrastructureInfo(infrastructure);
        }catch (Exception e){
            e.printStackTrace();
            accountRegisterService.deleteById(register.getId());
            accountRepositoryService.deleteById(account.getId());
            unitRepositoryService.deleteById(archiveUnit.getId());
            unitMemberMapper.deleteByPrimaryKey(unitMember.getId());
            inforConstRepositoryService.deleteInforConstItem(archiveUnit.getId());
            infrastructureRepositoryService.deleteInfrastructureInfo(archiveUnit.getId());
            return Result.body(id, ResultType.BUSINESS_ERROR).withMessage(e.getMessage());
        }
        //发送短信
        SendSms sendSms = new SendSms();
        //短信渠道
        sendSms.setSmsChannel("1");
        //短信模板编码
        sendSms.setSmsTemplateEncoded("sendRegisterAdopt");
        //待发送手机号
        String[] strings = new String[]{register.getRecorderTele()};
        sendSms.setPhoneNumbers(strings);
        //短信模板变量
        Map<String, String> map = new HashMap<>();
        map.put("account", register.getAccount());
        map.put("password", "Ywzd000111%@@");
        sendSms.setParamMap(map);
        return smsService.sendSms(sendSms);
    }
}